<script>
import { Upload } from 'element-ui';
import QRCode from 'qrcode';
import { getFileUploadCode, getFileUrlByCode } from '@const/fileLibraryApi.js';
import { hasIn } from 'lodash';
export default {
  name: 'MyUpload',
  components: { mUpload: Upload },
  data() {
    return {
      qrcodeImg: '',
      backVisible: false,
      qrcodeLoading: false,
      code: '',
    };
  },
  methods: {
    qrcodeBtn() {
      this.backVisible = true;
      this.qrcodeLoading = true;
      let originUrl = window.location.origin.includes('.com')
        ? window.location.origin
        : 'https://md.heng-tai.com.cn';
      this.$axios({
        url: getFileUploadCode,
        method: 'post',
      }).then((res) => {
        let code = hasIn(res, ['data', 'payload']) ? res.data.payload : '';
        if (!code) {
          this.$message({
            type: 'warning',
            message: '获取状态码失败，请联系管理员！',
          });
          return;
        }
        this.code = code;
        QRCode.toDataURL(
          `${originUrl}/guoke-deepexi-utils-server-h5/#/file?token=${this.$store.state.token}&code=${code}`
        )
          .then((url) => {
            this.qrcodeImg = url;
            this.qrcodeLoading = false;
          })
          .catch(() => {
            this.$message({
              type: 'error',
              message: '生成二维码失败，建议使用本地上传！',
            });
          });
      });
    },
    // 取消提示
    cancleConfirm() {
      this.$confirm(
        '还未检测到通过二维码上传的文件，是否取消二维码上传?',
        '提示',
        {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        }
      )
        .then(() => {
          this.backVisible = false;
        })
        .catch(() => {
          this.qrcodeLoading = false;
        });
    },
    backClick() {
      this.qrcodeLoading = true;
      this.$axios({
        url: getFileUrlByCode,
        method: 'post',
        data: { code: this.code },
      })
        .then((res) => {
          let imgUrl = hasIn(res, ['data', 'payload']) ? res.data.payload : '';
          if (!imgUrl) {
            this.cancleConfirm();
            return;
          }
          let mProps = this.$attrs['m-props'];
          if (mProps.type == 'other' && mProps.uploadFileType == '2') {
            mProps.urlObj[mProps.urlStr].push([
              imgUrl,
              mProps.urlObj[mProps.urlStr].length.toString(),
            ]);
          } else {
            mProps.urlObj[mProps.urlStr] = imgUrl;
          }
          this.backVisible = false;
        })
        .catch(() => {
          this.backVisible = false;
          this.$message({
            type: 'warning',
            message: '获取上传图片失败，建议使用本地上传！',
          });
        });
    },
  },
  render(h) {
    const attrsMethods = (slots) => {
      let values = Object.values(slots);
      let sList = [];
      values.forEach((vnodes) => {
        sList.push(vnodes);
      });
      return sList;
    };
    const qrcodeShow = (h) => {
      return this.backVisible
        ? h(
            'div',
            {
              class: { 'back-mask': true },
              on: {
                click: this.backClick,
              },
            },
            this.qrcodeImg
              ? [
                  h('el-image', {
                    class: { 'back-qrcode-img': true },
                    directives: [
                      { name: 'loading', value: this.qrcodeLoading },
                    ],
                    props: { fit: 'fitType', src: this.qrcodeImg },
                  }),
                  h(
                    'span',
                    {
                      class: { 'qrcode-icon': true },
                    },
                    [
                      h('icon-font', {
                        props: { icon: 'el-icon-mobile-phone' },
                      }),
                    ]
                  ),
                ]
              : []
          )
        : [];
    };
    const qrcodeBtn = (h) => {
      return h('i', { class: { 'iconfont icon-qrcode': true } });
    };

    let mProps = this.$attrs['m-props'];
    let flag = mProps.type === 'other' && mProps.uploadFileType === '1';

    return h('div', { class: { qrcode_upload_box: true } }, [
      h(
        'm-upload',
        {
          props: this.$attrs,
          on: this.$listeners,
          ref: 'mUpload',
        },
        attrsMethods(this.$slots)
      ),
      h(
        'el-button',
        {
          class: { qrcode_box: true, isShow_qrcode_box: flag },
          props: {
            circle: true,
            type: 'primary',
            disabled: this.$attrs.disabled,
          },
          attrs: { title: '手机上传二维码' },
          on: {
            click: this.qrcodeBtn,
          },
        },
        [qrcodeBtn(h)]
      ),
      qrcodeShow(h),
    ]);
  },
};
</script>
<style lang="less" scoped>
.qrcode_upload_box {
  position: relative;
  width: 100%;
  height: 100%;
  .qrcode_box {
    position: absolute;
    top: -16px;
    right: 0;
    transform: translate(50%, 50%);
    z-index: 99;
    background-color: #85aafd;
    border-color: #85aafd;
  }
  .isShow_qrcode_box {
    display: none;
  }
  .icon-qrcode {
    font-size: 24px;
  }

  .back-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.7);
    z-index: 100;
    display: flex;
    align-items: center;
    justify-content: center;
    .back-qrcode-img {
      width: 250px;
      height: 250px;
    }
    .qrcode-icon {
      position: fixed;
      width: 50px;
      height: 50px;
      background-color: rgba(255, 255, 255, 0.9);
      border-radius: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      > i {
        font-size: 40px;
      }
    }
  }
}
</style>
